package com.ydDev.charateranimation;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import GameTools.ydMath;
import GameTools.ydSprite;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.ColorDrawable;
import android.graphics.Canvas;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

	MainView sm;

	private Menu menu;

	Boolean gameState = true;

	String mScreenshotPath = Environment.getExternalStorageDirectory() + "";
	String file = "";

	Dialog choosePart;
	ArrayList<View> chooseCells;
	int cellSelected = 0;

	int jointSelected = 0;

	Dialog showPart;
	ArrayList<View> showCells;
	ArrayList<Boolean> showParts = new ArrayList<Boolean>();

	Dialog propertiesDialog;

	View MC;

	View controls;

	Boolean recording = false;
	Boolean playing = false;

	SeekBar seekbar;
	Boolean settingScale=false;

	private static final String TAG = MainActivity.class.getSimpleName();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ydSprite.context = getApplicationContext();

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// making it full screen
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// set our MainGamePanel as the View

		RelativeLayout rl = new RelativeLayout(this);

		ScrollView sv = new ScrollView(getApplicationContext());
		// / sv.addView(new StickMan(this));
		sm = new MainView(this);

		rl.addView(sm);
		setContentView(rl);
		Log.d(TAG, "View added");

		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(50, 50);
		lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		lp.addRule(RelativeLayout.CENTER_HORIZONTAL);

		LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		controls = layoutInflater.inflate(R.layout.tools_options, null);
		MC = layoutInflater.inflate(R.layout.media_controller, null);
		MC.setVisibility(View.GONE);
		rl.addView(MC.findViewById(R.id.linearLayoutMediaController));
		rl.addView(controls.findViewById(R.id.linearLayoutControls));

		((Button) controls.findViewById(R.id.buttonMediaController))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						controls.setVisibility(View.GONE);
						MC.setVisibility(View.VISIBLE);
					}

				});

		((Button) controls.findViewById(R.id.buttonProperties))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						propertiesDialog.show();
					}

				});
		
		((Button) controls.findViewById(R.id.buttonScale))
		.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if(settingScale){
					settingScale=false;
					seekbar.setVisibility(View.GONE);
				}
				else{
					settingScale=true;
					seekbar.setVisibility(View.VISIBLE);
				}
				
				
			}

		});

		((Button) MC.findViewById(R.id.buttonMCClose))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						controls.setVisibility(View.VISIBLE);
						MC.setVisibility(View.GONE);
					}

				});

		((Button) MC.findViewById(R.id.buttonMCPlay))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						if (playing) {
							playing = false;
							((Button) MC.findViewById(R.id.buttonMCPlay))
									.setBackgroundResource(R.drawable.mb1__play);
						} else {
							playing = true;
							((Button) MC.findViewById(R.id.buttonMCPlay))
									.setBackgroundResource(R.drawable.mb1__pause);

							recording = false;
							((Button) MC.findViewById(R.id.buttonMCRecord))
									.setBackgroundResource(R.drawable.mb1__record);
						}
						// sm.recordClicked();
						sm.setPlaying(playing);
					}

				});

		((Button) MC.findViewById(R.id.buttonMCRecord))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						if (recording) {
							recording = false;
							((Button) MC.findViewById(R.id.buttonMCRecord))
									.setBackgroundResource(R.drawable.mb1__record);
						} else {
							recording = true;
							((Button) MC.findViewById(R.id.buttonMCRecord))
									.setBackgroundResource(R.drawable.mb1__record_active);
						}
						// sm.recordClicked();
					}

				});

		((Button) MC.findViewById(R.id.buttonMCNext))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						sm.c1.step(0);
						if (recording) {
							sm.recordClicked();
						}
					}

				});

		((Button) MC.findViewById(R.id.buttonMCBack))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						sm.c1.step(1);
						if (recording) {
							sm.recordClicked();
						}
					}

				});

		for (int i = 0; i < 6; i++) {

			showParts.add(true);
		}
		// sm=new StickMan(getApplicationContext());

		// setContentView(sm);

		setChoosePartDialog();
		setShowPartDialog();
		setShowCheckBoxes();
		setChooseCheckBoxes();

		setPropertiesDialog();

		RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(500,
				50);
		lp2.addRule(RelativeLayout.CENTER_VERTICAL);
		lp2.addRule(RelativeLayout.CENTER_HORIZONTAL);

		seekbar = new SeekBar(this);
		seekbar.setLayoutParams(lp2);
		seekbar.setVisibility(View.GONE);
		seekbar.setMax(100);
		seekbar.setProgress(seekbar.getMax());
		rl.addView(seekbar);

		seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				// value.setText("SeekBar value is "+progress);
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}
		});
	}

	/*
	 * @Override public boolean onTouchEvent(MotionEvent event) {
	 * 
	 * if(!gameState){ viewAddRock.show(); }
	 * 
	 * return super.onTouchEvent(event);//false indicates the event is not
	 * consumed }
	 */

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		this.menu = menu;
		return true;
	}

	/*
	 * public boolean saveClicked(MenuItem item) { String mScreenshotPath =
	 * Environment.getExternalStorageDirectory() + ""; Bitmap bitmap =
	 * Bitmap.createBitmap(sm.getWidth(), sm.getHeight(),
	 * Bitmap.Config.ARGB_8888); sm.onDraw(new Canvas(bitmap)); try {
	 * OutputStream out = new BufferedOutputStream( new
	 * FileOutputStream(mScreenshotPath + "/" + System.currentTimeMillis() +
	 * ".jpg")); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); } catch
	 * (IOException e) { Log.w(TAG, e); } return true; }
	 */

	public boolean gameClicked(MenuItem item) {

		item.setChecked(true);

		// menu.findItem(R.id.menu_add_rock).setChecked(false);
		sm.setGameState(true);
		gameState = true;

		return true;
	}

	public boolean loadClicked(MenuItem item) {

		sm.loadClicked(mScreenshotPath + "/" + file);
		return true;
	}

	public boolean addRockClicked(MenuItem item) {

		item.setChecked(true);

		// menu.findItem(R.id.menu_game).setChecked(false);
		sm.setGameState(false);
		gameState = false;

		return true;
	}

	public boolean saveMapClicked(MenuItem item) {
		String mScreenshotPath = Environment.getExternalStorageDirectory() + "";
		sm.saveMap(mScreenshotPath + "/" + System.currentTimeMillis() + ".txt");

		return true;
	}

	public boolean chooseFileClicked(MenuItem item) {

		AlertDialog.Builder editalert = new AlertDialog.Builder(this);

		// editalert.setTitle("messagetitle");
		editalert.setMessage("Enter file name");

		final EditText input = new EditText(this);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT);
		input.setLayoutParams(lp);
		editalert.setView(input);

		editalert.setPositiveButton("Enter file name",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						file = input.getText().toString();
						(menu.findItem(R.id.menu_file_name)).setTitle(file);
					}
				});

		editalert.show();

		return true;
	}

	public boolean choosePartClicked(MenuItem item) {
		choosePart.show();
		return true;
	}

	public boolean showPartClicked(MenuItem item) {
		showPart.show();
		return true;
	}

	public boolean saveClicked(MenuItem item) throws IOException {
		sm.saveClicked(mScreenshotPath + "/" + file);
		return true;
	}

	public View createChooseCell(String text, final int tag) {
		View cell = new LinearLayout(this);

		cell = LayoutInflater.from(getBaseContext()).inflate(
				R.layout.choose_part_cell, null);

		cell.setTag(tag);

		((TextView) cell.findViewById(R.id.textViewPart)).setText(text + "  "
				+ cell.getTag());

		cell.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				cellSelected = tag;

				setChooseCheckBoxes();
				sm.setSelectedPart(tag);

				// choosePart.hide();
				// showPart.hide();
			}

		});
		(cell.findViewById(R.id.checkBox))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						cellSelected = tag;
						setChooseCheckBoxes();
						sm.setSelectedPart(tag);

						// choosePart.hide();
						// showPart.hide();
					}

				});

		return cell;
	}

	public View createShowCell(String text, final int tag) {
		View cell = new LinearLayout(this);

		cell = LayoutInflater.from(getBaseContext()).inflate(
				R.layout.choose_part_cell, null);

		cell.setTag(tag);

		((TextView) cell.findViewById(R.id.textViewPart)).setText(text + "  "
				+ cell.getTag());

		cell.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				if (showParts.get(tag)) {
					showParts.set(tag, false);
				} else {
					showParts.set(tag, true);
				}

				setShowCheckBoxes();
				// choosePart.hide();
				// showPart.hide();
			}

		});
		(cell.findViewById(R.id.checkBox))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {

						if (showParts.get(tag)) {
							showParts.set(tag, false);
						} else {
							showParts.set(tag, true);
						}
						setShowCheckBoxes();
						// choosePart.hide();
						// showPart.hide();
					}

				});

		return cell;
	}

	public View createPropertiesCell(String text, final int tag) {

		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(50, 50);
		lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		lp.addRule(RelativeLayout.CENTER_HORIZONTAL);

		View cell = new LinearLayout(this);

		cell = LayoutInflater.from(getBaseContext()).inflate(
				R.layout.limb_properties_cell, null);

		cell.setTag(tag);

		((TextView) cell.findViewById(R.id.textViewTitle)).setText(text);

		return cell;
	}

	public void setChoosePartDialog() {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		chooseCells = new ArrayList<View>();

		choosePart = new Dialog(MainActivity.this);

		choosePart.setContentView(R.layout.choose_part_dialog);

		choosePart.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));

		chooseCells.add(createChooseCell("Head", 0));
		chooseCells.add(createChooseCell("Torso", 1));
		chooseCells.add(createChooseCell("Right Arm", 2));
		chooseCells.add(createChooseCell("Left Arm", 3));
		chooseCells.add(createChooseCell("Right Leg", 4));
		chooseCells.add(createChooseCell("Left Leg", 5));

		View cell = new LinearLayout(this);

		cell = LayoutInflater.from(getBaseContext()).inflate(
				R.layout.choose_part_joint_cell, null);

		cell.setTag(0);

		for (View v : chooseCells) {
			((LinearLayout) choosePart
					.findViewById(R.id.linearLayoutCellHolder)).addView(v);
		}

		((LinearLayout) choosePart.findViewById(R.id.linearLayoutCellHolder))
				.addView(cell);
	}

	public void setShowPartDialog() {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		showCells = new ArrayList<View>();

		showPart = new Dialog(MainActivity.this);

		showPart.setContentView(R.layout.choose_part_dialog);

		showPart.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));

		showCells.add(createShowCell("Head", 0));
		showCells.add(createShowCell("Torso", 1));
		showCells.add(createShowCell("Right Arm", 2));
		showCells.add(createShowCell("Left Arm", 3));
		showCells.add(createShowCell("Right Leg", 4));
		showCells.add(createShowCell("Left Leg", 5));

		for (View v : showCells) {
			((LinearLayout) showPart.findViewById(R.id.linearLayoutCellHolder))
					.addView(v);
		}

	}

	public void setPropertiesDialog() {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		propertiesDialog = new Dialog(MainActivity.this);

		propertiesDialog.setContentView(R.layout.choose_part_dialog);

		propertiesDialog.getWindow().setBackgroundDrawable(
				new ColorDrawable(android.graphics.Color.TRANSPARENT));

		((LinearLayout) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder))
				.addView(createPropertiesCell("Head", 0));
		((LinearLayout) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder))
				.addView(createPropertiesCell("Torso", 1));
		((LinearLayout) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder))
				.addView(createPropertiesCell("Right Arm", 2));
		((LinearLayout) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder))
				.addView(createPropertiesCell("Left Arm", 3));
		((LinearLayout) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder))
				.addView(createPropertiesCell("Right Leg", 4));
		((LinearLayout) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder))
				.addView(createPropertiesCell("Left Leg", 5));

		Button set = new Button(this);
		set.setText("Set");

		set.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				setLimbProperties();
				propertiesDialog.hide();
			}

		});

		Button cancel = new Button(this);
		cancel.setText("Cancel");

		cancel.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				propertiesDialog.hide();
			}

		});

		((LinearLayout) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder)).addView(set);
		((LinearLayout) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder)).addView(cancel);
	}

	public void setChooseCheckBoxes() {

		for (View v : chooseCells) {

			if ((Integer) v.getTag() == cellSelected)
				((CheckBox) v.findViewById(R.id.checkBox)).setChecked(true);
			else
				((CheckBox) v.findViewById(R.id.checkBox)).setChecked(false);
		}

	}

	public void setShowCheckBoxes() {

		for (View v : showCells) {

			((CheckBox) v.findViewById(R.id.checkBox)).setChecked(showParts
					.get((Integer) v.getTag()));

		}

		sm.c1.showParts(showParts, jointSelected);

	}

	public void joint1Clicked(View v) {
		jointSelected = 0;
		LinearLayout l = (LinearLayout) choosePart
				.findViewById(R.id.linearLayoutChooseJoint);
		((CheckBox) l.findViewById(R.id.checkBoxJoint1)).setChecked(true);
		((CheckBox) l.findViewById(R.id.checkBoxJoint2)).setChecked(false);

		sm.c1.showParts(showParts, jointSelected);
	}

	public void joint2Clicked(View v) {
		jointSelected = 1;

		LinearLayout l = (LinearLayout) choosePart
				.findViewById(R.id.linearLayoutChooseJoint);
		((CheckBox) l.findViewById(R.id.checkBoxJoint1)).setChecked(false);
		((CheckBox) l.findViewById(R.id.checkBoxJoint2)).setChecked(true);

		sm.c1.showParts(showParts, jointSelected);
	}

	private void setLimbProperties() {
		ArrayList<Double> angularVelocities = new ArrayList<Double>();
		for (int i = 0; i < ((ViewGroup) propertiesDialog
				.findViewById(R.id.linearLayoutCellHolder)).getChildCount() - 2; ++i) {
			View nextChild = ((ViewGroup) propertiesDialog
					.findViewById(R.id.linearLayoutCellHolder)).getChildAt(i);
			double a = Double.parseDouble(((EditText) nextChild
					.findViewById(R.id.editTextAngularVelocity)).getText()
					.toString());
			angularVelocities.add((double) ydMath.degreesToRads((float) a));
		}

		sm.c1.setAngularVelocities(angularVelocities);
	}

	/*
	 * public void recordClicked(View v){ sm.recordClicked(); }
	 */

}
